import axios from 'axios'
import store from "@/store";
import router from "@/router";
// import Cache from '@/utils/cache'
import errorCode from '@/utils/errorCode'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 1000 *60 // 超时时间
})

// 请求拦截器
service.interceptors.request.use(config => {
  config.headers['Request-Source'] = 'fytWeb'
  // ////console.log('config', config)
  const token = store.getters.token || localStorage.getItem('userToken')
  ////console.log('token', token,store,localStorage.getItem('token'));
  if (token) {
    config.headers['authorization'] = token
  }
  return config
}, error => {
  ////console.log("------------------->>>>>>>>",error)
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
  const code = res.data.code || 200
  // 获取错误信息
  const msg = errorCode[code] || res.data.msg || errorCode['default']
  // 二进制数据则直接返回
  if (res.request.requestType === 'blob' || res.request.requestType === 'arrayBuffer') {
    return res.data
  }
  if (code === 500) {
    //console.log('err>>>>>' + msg) // for debug
    return Promise.reject(new Error(msg))
  } else if (code >= 300) {
   
    if (code === 6006) {
      // 用户登录认证失败,请重新登录(跳转至首页)
      store.commit("SET_TOKEN", '');
      router.push('/')
      return;
    }
    return Promise.reject('error')
  } else {
    return res.data
  }
}, error => {
  ////console.log('err' + error)
  let { message } = error
  if (message === 'Network Error') {
    message = '后端接口连接异常'
  } else if (message.includes('timeout')) {
    message = '系统接口请求超时'
  } else if (message.includes('Request failed with status code')) {
    message = '系统接口' + message.substr(message.length - 3) + '异常'
  }
  // Message({
  //   message: message,
  //   type: 'error',
  //   duration: 5 * 1000
  // })
  return Promise.reject(error)
})

/**
 * 通用请求方法
 * @param {Object} options 请求配置
 */
function request(options) {
  return service({
    method: options.method || 'GET',
    url: options.url,
    data: options.data,
    params: options.params,
    ...options
  })
}

// 封装GET/POST快捷方法
export function get(url, params, options = {}) {
  return request({
    url,
    params,
    method: 'GET',
    ...options
  })
}

export function post(url, data, options = {}) {
  return request({
    url,
    data,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      ...options.headers
    },
    ...options
  })
}



export default request
